#define _GNU_SOURCE
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>

//初始化互斥锁
static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

void *add_thread(void *argv){
    int *p = argv;

    //累加变量前加索
    pthread_mutex_lock(&counter_mutex);
    *p = *p + 1;
    //释放锁
    pthread_mutex_unlock(&counter_mutex);
    return NULL;
}

int main(int argc, char const *argv[])
{
    int num = 0;
    pthread_t threads[20000];
    for (int i = 0; i < 20000; i++)
    {
        pthread_create(&threads[i],NULL,add_thread,&num);
    }
    for (int i = 0; i < 20000; i++)
    {
        pthread_join(threads[i],NULL);
    }
    printf("num = %d",num);

    //销毁索
    pthread_mutex_destroy(&counter_mutex);

    return 0;
}



